<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24" >
            <a-form-item label="电价方案名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['name',validatorRules.name]" placeholder="请输入电价方案名称" ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="方案状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-decorator="['status',validatorRules.status]" placeholder="请选择方案状态">
                <a-select-option value="默认方案">默认方案</a-select-option>
                <a-select-option value="备用方案">备用方案</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="电价方案详情" :key="refKeys[0]" :forceRender="true">
        <j-editable-table
          :ref="refKeys[0]"
          :loading="chargeElectricityDetailTable.loading"
          :columns="chargeElectricityDetailTable.columns"
          :dataSource="chargeElectricityDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :actionButton="true"/>
      </a-tab-pane>
    </a-tabs>
    <a-row v-if="showFlowSubmitButton" style="text-align: center;width: 100%;margin-top: 16px;"><a-button @click="handleOk">提 交</a-button></a-row>
  </a-spin>
</template>

<script>

  import pick from 'lodash.pick'
  import { getAction } from '@/api/manage'
  import { FormTypes,VALIDATE_NO_PASSED,getRefPromise, validateFormAndTables } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'ChargeElectricityForm',
    mixins: [JEditableTableMixin],
    components: {
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          name:{rules: [{ required: true, message: '请输入方案名称!' }]},
          status:{rules: [{ required: true, message: '请选择方案状态!' }]},
        },
        refKeys: ['chargeElectricityDetail', ],
        tableKeys:['chargeElectricityDetail', ],
        activeKey: 'chargeElectricityDetail',
        // 电价方案详情
        chargeElectricityDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '起始时间',
              key: 'startTime',
              type: FormTypes.select,
              width:"200px",
              placeholder: '请选择${title}',
              defaultValue:'',
              options: [{ label: '0:00', value: '0' }, { label: '1:00', value: '1' }, { label: '2:00', value: '2' }, { label: '3:00', value: '3' },
                { label: '4:00', value: '4' }, { label: '5:00', value: '5' }, { label: '6:00', value: '6' }, { label: '7:00', value: '7' },
                { label: '8:00', value: '8' }, { label: '9:00', value: '9' }, { label: '10:00', value: '10' }, { label: '11:00', value: '11' }, 
                { label: '12:00', value: '12' }, { label: '13:00', value: '13' }, { label: '14:00', value: '14' }, { label: '15:00', value: '15' },
                { label: '16:00', value: '16' }, { label: '17:00', value: '17' }, { label: '18:00', value: '18' }, { label: '19:00', value: '19' },
                { label: '20:00', value: '20' }, { label: '21:00', value: '21' }, { label: '22:00', value: '22' }, { label: '23:00', value: '23' },
              ]
            },
            {
              title: '结束时间',
              key: 'endTime',
              type: FormTypes.select,
              width:"200px",
              placeholder: '请选择${title}',
              defaultValue:'',
              options: [{ label: '0:59', value: '0' }, { label: '1:59', value: '1' }, { label: '2:59', value: '2' }, { label: '3:59', value: '3' },
                { label: '4:59', value: '4' }, { label: '5:59', value: '5' }, { label: '6:59', value: '6' }, { label: '7:59', value: '7' },
                { label: '8:59', value: '8' }, { label: '9:59', value: '9' }, { label: '10:59', value: '10' }, { label: '11:59', value: '11' }, 
                { label: '12:59', value: '12' }, { label: '13:59', value: '13' }, { label: '14:59', value: '14' }, { label: '15:59', value: '15' },
                { label: '16:59', value: '16' }, { label: '17:59', value: '17' }, { label: '18:59', value: '18' }, { label: '19:59', value: '19' },
                { label: '20:59', value: '20' }, { label: '21:59', value: '21' }, { label: '22:59', value: '22' }, { label: '23:59', value: '23' },
              ]
            },
            {
              title: '价格',
              key: 'price',
              type: FormTypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{required: true, message: '${title}不能为空'}]
            },
          ]
        },
        url: {
          add: "/chargeElectricity/chargeElectricity/add",
          edit: "/chargeElectricity/chargeElectricity/edit",
          queryById: "/chargeElectricity/chargeElectricity/queryById",
          chargeElectricityDetail: {
            list: '/chargeElectricity/chargeElectricity/queryChargeElectricityDetailByMainId'
          },
        }
      }
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：false流程表单 true普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      checkFormCompleteness(rows){
        let timeSlots = new Array(24).fill(false);
        for (let i = 0; i < rows.length; i++) {
          let row = rows[i];
          let startTime = parseInt(row.startTime);
          let endTime = parseInt(row.endTime);
          if (startTime <= endTime) {
            // 如果起始时间小于等于结束时间，直接进行填充
            for (let time = startTime; time <= endTime; time++) {
              if (timeSlots[time]) {
                return false; // 时间重复，返回 false
              }
              timeSlots[time] = true;
            }
          }else {
            // 如果起始时间大于结束时间，则说明时间段跨越了两天
            for (let time = startTime; time <= 23; time++) {
              if (timeSlots[time]) {
                return false; // 时间重复，返回 false
              }
              timeSlots[time] = true;
            }
            for (let time = 0; time <= endTime; time++) {
              if (timeSlots[time]) {
                return false; // 时间重复，返回 false
              }
              timeSlots[time] = true;
            }
          }
        }
        // 检查 timeSlots 数组是否包含了连续的 0-23 时间段，并且所有时间点都被选择了一次
        for (let i = 0; i < 24; i++) {
          if (!timeSlots[i]) {
            return false;
          }
        }
        return true;
      },
      /** 确定按钮点击事件 */
      handleOk() {
        /** 触发表单验证 */
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          if(!this.checkFormCompleteness(formData.chargeElectricityDetailList)){
            this.$message.error('请选择完整的时间闭环！');
            return;
          }
          console.log(formData);
          // 发起请求
          return this.request(formData)
        }).catch(e => {
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      },
      addBefore(){
        this.form.resetFields()
        this.chargeElectricityDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        let fieldval = pick(this.model,'name','status')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.chargeElectricityDetail.list, params, this.chargeElectricityDetailTable)
        }
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          chargeElectricityDetailList: allValues.tablesValue[0].values,
        }
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          })
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'name','status'))
      },

    }
  }
</script>

<style scoped>
</style>